<?php

namespace app\controller\admin\module\common\components;

use app\components\traits\Singleton;
use Exception;
use think\exception\ValidateException;
use think\facade\Filesystem;

class Upload
{
    use Singleton;
    protected array $uploadDomain = [
        '',
        HTTP_STATIC_LOCAL_URL,  //本地
        HTTP_STATIC_CDN_URL,            //CDN
    ];

    /**
     * 上传文件，可选模式
     * @param string $mode
     * @return array
     */
    public function file(string $mode): array
    {
        try {
            $res = $this->checkFile($mode);
            if($res['code'] != 200){
                return responseArrayMsg($res['msg']);
            }
            $uploadModel = getSettingOptionsCache('uploader.mode', 1);   //上传模式，默认本地

            $path = Filesystem::disk('public')->putFile('upload', $res['data']['file']);
            //结果是 $path = upload/20200825\***.jpg

            //图片路径，Filesystem::getDiskConfig('public','url')功能是获取public目录下的storage，
            $picCover = Filesystem::getDiskConfig('public', 'url') . DIRECTORY_SEPARATOR . str_replace('\\','/',$path);
            //结果是 $picCover = storage/upload/20200825/***.jpg
            $url = $this->uploadDomain[$uploadModel] . $picCover;
            $uploadModel == 2 and uploadAliOssFile($picCover);  //上传至阿里云oss
            return responseArrayMsg('上传成功!', 200,  [
                'url' => $url,
            ]);
        } catch (ValidateException $e) {
            return responseArrayMsg($e->getError());
        } catch (Exception $e) {
            return responseArrayMsg($e->getMessage());
        }

    }

    /**
     * 删除文件
     * @param string $path  文件路径
     * @return array
     */
    public function delete(string $path): array
    {
        if(empty($path)){
            return responseArrayMsg('文件路径不能为空');
        }
        //删除操作...


        return responseArrayMsg('删除成功', 200);
    }

    /**
     * 校验文件
     * @param $mode
     * @return array
     * @throws Exception
     */
    private function checkFile($mode): array
    {
        $file = request()->file('file');
        try {
            validate(['file' => $file], ['file' => ['fileSize:' . getSettingOptionsCache('uploader.upload_' . $mode . '_size', 0) . ',fileExt:' . getSettingOptionsCache('uploader.upload_' . $mode . '_ext', 'log')]]);
            return responseArrayMsg('通过', 200, ['file' => $file]);
        }catch (ValidateException $e){
            return responseArrayMsg($e->getError());
        }catch (Exception $e){
            return responseArrayMsg($e->getMessage());
        }
    }

}